package com.tacademy.lbs.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.tacademy.lbs.server.model.Place;

@SuppressWarnings("serial")
public class GetLocationFromIDServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String id = request.getParameter("id");
		if (id == null || id.trim().length() == 0) {
			return;
		}
		response.setHeader("Content-Encoding", "utf-8");
		response.setCharacterEncoding("utf-8");
		StringBuilder xmlStrBuilder = new StringBuilder();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  where id == '").append(id).append("'");
			
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			if (places.size() == 0) {
				return;
			}
			Place place = places.get(0);
			
			if (place.getLocation() == null) {
				place.setLocation("");
			}
			String[] locationArr = place.getLocation().split("@");
			String placeName = "";
			String coordinate = "";
			if (locationArr != null && locationArr.length == 2) {
				placeName = locationArr[0];
				coordinate = locationArr[1];
			}
			
			xmlStrBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			xmlStrBuilder.append("<place>\n");
			xmlStrBuilder.append("\t<key>").append(place.getKey()).append("</key>\n");
			xmlStrBuilder.append("\t<placeName>").append(placeName).append("</placeName>\n");
			xmlStrBuilder.append("\t<coordinate>").append(coordinate).append("</coordinate>\n");
			xmlStrBuilder.append("\t<id>").append(place.getId()).append("</id>\n");
			xmlStrBuilder.append("\t<date>").append(place.getDate()).append("</date>\n");
			xmlStrBuilder.append("\t<user>").append(place.getUser()).append("</user>\n");
			xmlStrBuilder.append("\t<count>").append(place.getCount()).append("</count>\n");
			xmlStrBuilder.append("</place>\n");
			PrintWriter writer = response.getWriter();
			writer.write(xmlStrBuilder.toString());
			writer.flush();
		} finally {
			pm.close();
		}
	}
}
